package com.example.demo.controller;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.User;
import com.example.demo.services.IUserService;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.StringUtil;
import com.example.demo.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j//日志注解
@Api(tags = "用户注解")
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/reg")
    public AppResult resister(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat)
    {
        //判断两次密码是否一样
        if(!password.equals(passwordRepeat))
        {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //写入数据
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);


        //密码
        //生成盐
        String salt= UUIDUtil.uuid_32();
        //加密
        String saltPassword= MD5Util.md5salt(password,salt);
        user.setPassword(saltPassword);
        user.setSalt(salt);

        userService.createNormalUser(user);
        return  AppResult.success();
    }


    /**
     * 用户登录
     * @param request
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username")  @NonNull String username,
                           @ApiParam("密码") @RequestParam("password")  @NonNull String password)
    {
        //1.调用service中的login方法，返回user对象
        User user=userService.login(username,password);
        if(user==null)
        {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2.如果登录成功就把User对象返回到Session作用域中
        HttpSession session=request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //3.返回结果
        return AppResult.success();
    }


    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserinfo(HttpServletRequest request,
                                       @ApiParam("用户ID") @RequestParam(value = "id",required = false) Long id)
    {
        User user=null;
        //1.如果id为空从session中获取用户信息
        if(id==null)
        {
            HttpSession session=request.getSession(false);
            //判断登录信息是否有效
            if(session==null || session.getAttribute(AppConfig.USER_SESSION)==null)
            {
                //返回错误
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            }
            //从session中获取当前用户登录信息
            user=(User) session.getAttribute(AppConfig.USER_SESSION);
        }
        else{
        //2.如果id不为空，从数据库根据id查询信息
        user=userService.selectById(id);

        }
        //判断用户是否为空
        if(user==null)
        {
            //返回错误
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        //返回正常的结果
        return AppResult.success(user);
    }

    @ApiOperation("用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request)
    {
        HttpSession session=request.getSession(false);
        if(session!=null)
        {
            log.info("退出成功");
            //如果session在线，就直接注销session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return AppResult
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                 @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {
        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }

        // 从session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        // 4. 调用Service中的方法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的用户信息
        user = userService.selectById(user.getId());
        // 6. 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回结果
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        if(!newPassword.equals(passwordRepeat))
        {
            return AppResult.failed(ResultCode.FAILED);
        }
        HttpSession session=request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);

        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        if(session!=null)
        {
            session.invalidate();
        }
        return AppResult.success();
    }
}
